/**
 * Created by Ysssssss on 2021/5/11.
 */

import React, { useState, useEffect, useRef, useCallback } from 'react'
import {useDispatch, useSelector} from "react-redux";
import { getProductPropertyList } from "@sagas/productCenter";
import ProductPropertyEditModal from "@components/productCenter/modal/ProductPropertyEditModal";
import DoubleCheck from "@common/presentational/DoubleCheck";
import { Row, Col, Dropdown, Menu } from 'antd'
import {CloseOutlined} from "@ant-design/icons";
import notify from "@utils/tip";

const ProductDetailProperty = props => {
    const { value = [], onChange, productNature } = props
    const [ visible, setVisible ] = useState(false)
    const [propertyItemsMap, setPropertyItemsMap] = useState({})
    const [{usingPropertyList, leftPropertyItemsMap}, setUsingPropertyInfo] = useState({usingPropertyList: [], leftPropertyItemsMap: {}})
    const { productPropertyList }= useSelector(state => state.productCenter)
    const dispatch = useDispatch()
    const productPropertyEditModal = useRef()

    const getPropertyList = useCallback(() => {
        dispatch(getProductPropertyList({ productNature }))
    }, [productNature])

    useEffect(getPropertyList, [])

    useEffect(() => {
        let _propertyItemsMap = {}
        productPropertyList.forEach(property => {
            _propertyItemsMap[property.name] = property.items
        })
        setPropertyItemsMap(_propertyItemsMap)
    }, [productPropertyList])

    useEffect(() => {
        let _leftPropertyItemsMap = {}
        let _usingPropertyList = value.map(item => {
            _leftPropertyItemsMap[item.name] = (propertyItemsMap[item.name] || []).filter(name => !item.items.includes(name))
            return item.name
        })
        setUsingPropertyInfo({
            usingPropertyList: _usingPropertyList,
            leftPropertyItemsMap: _leftPropertyItemsMap
        })
    }, [value, propertyItemsMap])

    const addProperty = ({ key }) => {
        if (key === 'createProperty') {
            productPropertyEditModal.current?.show({})
            setVisible(false)
            return;
        }
        onChange([
            ...value,
            {
                name: key,
                items: propertyItemsMap[key] || []
            }
        ])
    }

    const editProperty = (item) => {
        productPropertyEditModal.current?.show({...item})
    }

    const deletePropertyAndItems = (index, subIndex) => {
        onChange([
            ...value.slice(0, index),
            ...(subIndex === undefined ? [] : [{
                ...value[index],
                items: [
                    ...value[index].items.slice(0, subIndex),
                    ...value[index].items.slice(subIndex + 1),
                ]
            }]),
            ...value.slice(index + 1),
        ])
    }

    const addPropertyItems = (index, { key }) => {
        if (value.length >=3) {
            notify('最多支持添加三个规格属性组')
            return ;
        }
        onChange([
            ...value.slice(0, index),
            {
                ...value[index],
                items: [
                    ...value[index].items,
                    key
                ]
            },
            ...value.slice(index + 1),
        ])
    }

    const getLeftPropertyMenu = () => {
        let menuList = []
        productPropertyList.forEach(item => {
            if (usingPropertyList.includes(item.name)) return;
            menuList.push(
                <Menu.Item key={item.name}>{item.name}</Menu.Item>
            )
        })
        return (
            <Menu onClick={addProperty}>
                { menuList }
                { menuList.length ? (
                    <Menu.Divider />
                ) : null }
                <Menu.Item key="createProperty">
                    <div className="clr-green">+ 新建</div>
                </Menu.Item>
            </Menu>
        )
    }

    return (
        <div className="flex">
            <Dropdown overlay={getLeftPropertyMenu()}
                      onVisibleChange={setVisible}
                      visible={visible}
                      trigger={['click']}
            >
                <span className="clr-green cur-poi flex-vertical-center" style={{height: '32px'}}>选择规格属性组</span>
            </Dropdown>
            { value.map((item, index) => (
                <div className="pd-16 bg-f5 mgt-16 w-100" key={item.name}>
                    <div className="flex-row-between">
                        <span>{ item.name }</span>
                        <div>
                            <span className="cur-poi" onClick={editProperty.bind(this, item)}>编辑</span>
                            <DoubleCheck onClick={deletePropertyAndItems.bind(this, index, undefined)}>
                                <span className="cur-poi mgl-16">删除</span>
                            </DoubleCheck>
                        </div>
                    </div>
                    <div className="product-property-items-list">
                        { item.items.map((sub, i) => (
                            <div className="product-property-item" key={sub}>
                                <span className="pdr-16">{ sub }</span>
                                <CloseOutlined className="cur-poi ft-12 ft-clr-ml" onClick={deletePropertyAndItems.bind(this, index, i)}/>
                            </div>
                        )) }
                        { leftPropertyItemsMap[item.name]?.length ? (
                            <Dropdown
                                trigger={['click']}
                                overlay={(
                                    <Menu onClick={addPropertyItems.bind(this, index)}>
                                        { leftPropertyItemsMap[item.name].map(leftItem => (
                                            <Menu.Item key={leftItem}>{leftItem}</Menu.Item>
                                        )) }
                                    </Menu>
                                )}
                            >
                                <span className="add-property-items">
                                    添加属性项
                                </span>
                            </Dropdown>
                        ) : null  }
                    </div>
                </div>
            )) }
            <ProductPropertyEditModal
                ref={productPropertyEditModal}
                productNature={productNature}
                callback={getPropertyList}
            />
        </div>
    )
}

export default ProductDetailProperty